package com.jiajia.server.config.security.compontent;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ZSJia
 * @date 2021/8/10 010 - 19:38
 */
@Component
public class JwtAuthencationTokenFifter extends OncePerRequestFilter {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private JwtTokenUtils jwtTokenUtils;
    @Autowired
    @Lazy
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String header = httpServletRequest.getHeader(tokenHeader);
                //存在token 并且是合法的
        if (header!=null && header.startsWith(tokenHead)){
            //截图头消息获取token
            String autoken = header.substring(tokenHead.length());
            //根据工具类获取用户名
            String username = jwtTokenUtils.getUserNameFromToken(autoken);
            //token存在但是security全局上下文不存在说明未登录
            if (username!=null && SecurityContextHolder.getContext().getAuthentication()==null){
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                //获取token
                String token = jwtTokenUtils.generateToken(userDetails);
                //判断token是否有效  并设置对象
                if (jwtTokenUtils.validateToken(autoken,userDetails)){
                    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                                                                        new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
                    usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetails(httpServletRequest));
                    SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
                }

            }


        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
